$(function(){
	$(":input[type='submit']").on("click",function(){
		$("#form-data").submit();
	});
	
	$("#add-section-list-row").on("click",function(event){
		add(event,null);
	});
	
	getChannels();
	changeSelect();
});
function del(button){
	var tr = $(button).parent().parent();
	var id_input = tr.find(":input[type='hidden'][name='id']");
	if(id_input!=undefined){
		var id = id_input.val();
		console.debug(id);
		if(id!=-1){
			$.get("delete.jspx?id="+id);
		}
	}
	tr.remove();
}

function add(event,data){
	if(data===null){
		data={orderid:1};
	}
	var template_html = template("row-template",data);
	$("#section-list-container").append(template_html);
	event.preventDefault();
	
	$(".del-section-list-row").on("click",function(event){
		event.preventDefault();
		del(this);
	});
}
function getChannels(){
	var channel_select = $("#channel_select");
	$.get("../channel/getJson.jspx?pageable=false",function(data){
		var channels = data.datarows;
		if(channels!=null){
			var option0 = channel_select.find("option:first");
			channel_select.empty();
			channel_select.append(option0);
			$.each(channels,function(index,element){
				channel_select.append("<option value=\""+element.id+"-"+element.orderid+"\">"+element.name+"</option>");
			});
		}
	});
}

function changeSelect(){
	$("#channel_select").on("change",function(event){
		var values = $(this).val().split("-");
		var id = values[0];
		if(id==0){
			return;
		}
		var orderid = values[1];
		var text = $(this).find("option:selected").text();
		var data = {
				name:text,
				linkurl:"channel/id_"+id+".jspx",
				orderid:orderid
		};
		
		add(event,data);
	});
}